package cn.vinord.Util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

public class JavaBeanUtil {
	public static MultiValueMap<String, String> convertBeanToMap(Object bean) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		@SuppressWarnings("rawtypes")
		Class type = bean.getClass();
		MultiValueMap<String, String> returnMap = new LinkedMultiValueMap<>();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (!propertyName.equals("class")) {
				Method readMethod = descriptor.getReadMethod();
				Object result = readMethod.invoke(bean, new Object[0]);
				if (result != null) {
					returnMap.add(propertyName, result.toString());
				} else {
					returnMap.add(propertyName, "");
				}
			}
		}
		return returnMap;
	}
}
